use std::sync::Arc;
use std::time::Duration;
use tokio::time;
use tracing::{info, Level};
use tracing_subscriber::FmtSubscriber;

use protoactor_rs::actor::{Actor, ActorContext};
use protoactor_rs::cluster::{ClusterConfig, ClusterSystem, ConsulConfig, ConsulProvider};
use protoactor_rs::remote::{Config as RemoteConfig, Remote};
use protoactor_rs::system::ActorSystem;

#[tokio::main]
async fn main() {
    // 设置日志
    let subscriber = FmtSubscriber::builder()
        .with_max_level(Level::INFO)
        .finish();
    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
    
    // 解析命令行参数
    let args: Vec<String> = std::env::args().collect();
    let port = if args.len() > 1 {
        args[1].parse::<u16>().unwrap_or(8000)
    } else {
        8000
    };
    
    // 创建Actor系统
    let system = ActorSystem::new();
    
    // 配置远程通信
    let remote_config = RemoteConfig::new()
        .with_host(&format!("127.0.0.1:{}", port))
        .build();
    
    // 创建远程模块
    let remote = Arc::new(Remote::new(system.clone(), remote_config));
    remote.start().await.expect("Failed to start remote");
    
    // 创建一个基于Consul的集群提供者
    let consul_config = ConsulConfig {
        address: "http://127.0.0.1:8500".to_string(),
        service_prefix: "protoactor".to_string(),
        ..Default::default()
    };
    
    let consul_provider = Arc::new(ConsulProvider::new(consul_config)
        .await
        .expect("Failed to create Consul provider"));
    
    // 配置集群
    let cluster_config = ClusterConfig {
        name: format!("node-{}", port),
        host: "127.0.0.1".to_string(),
        port,
        heartbeat_interval: 5,
        unreachable_timeout: 15,
        down_timeout: 30,
    };
    
    // 创建集群系统
    let (mut cluster_system, mut event_rx) = ClusterSystem::new(
        consul_provider,
        cluster_config,
        remote,
    );
    
    // 启动集群
    cluster_system.start().await.expect("Failed to start cluster");
    
    info!("Cluster node started on port {}", port);
    
    // 处理集群事件
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            info!("Received cluster event: {:?}", event);
        }
    });
    
    // 每5秒输出集群成员信息
    loop {
        time::sleep(Duration::from_secs(5)).await;
        
        // 使用公共API获取成员列表
        match cluster_system.get_members().await {
            Ok(members) => {
                info!("Cluster members:");
                for member in members {
                    info!(" - {} at {}:{} (status: {:?})", 
                          member.id, 
                          member.host, 
                          member.port, 
                          member.status);
                }
            },
            Err(e) => {
                info!("Failed to get cluster members: {:?}", e);
            }
        }
    }
} 